//
//  HJQrCodeController.m
//  KaiChat
//
//  Created by lx on 2024/1/12.
//

#import "HJQrCodeController.h"
#import "HJButton.h"
#import "HJAlertController.h"
#import <Photos/Photos.h>
#import "HJShareController.h"

@interface HJQrCodeController ()

@property (nonatomic, weak) UIImageView *QrCodeImageView;
@property (nonatomic, weak) UIImageView *shareQrCodeImageView;
@property (nonatomic, weak) UIView *shareView;
@property (nonatomic, strong) NSDictionary *qrCodeDict;

@end

@implementation HJQrCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.titleTextColor = UIColor.whiteColor;
    self.navigationBar.alpha = 0;
    self.navigationBar.title = @"QR Code";
    [self.navigationBar.backBarButton whiteColor];

    UIImageView *backgroundImageView = [UIImageView addToView:self.view];
    backgroundImageView.userInteractionEnabled = YES;
    backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;    
    [backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    UIImageView *contentView = [UIImageView addToView:self.view];
    contentView.userInteractionEnabled = YES;
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(18);
        make.centerX.offset(0);
        make.centerY.offset(-20);
        make.height.offset(452);
    }];
    
//    dispatch_async_main_queue(^{
        backgroundImageView.image = [UIImage imageWithContentsOfName:@"qrCode_bg" type:@"png"];
        contentView.image = [UIImage imageNamed:@"qrcode_content_bg"];
//    });
    
    UIImageView *avatarImageView = [UIImageView addToView:contentView];
    avatarImageView.backgroundColor = UIColor.whiteColor;
    avatarImageView.addCornerRadius(40);
    avatarImageView.layer.borderColor = UIColor.whiteColor.CGColor;
    avatarImageView.layer.borderWidth = 2;
    [avatarImageView tj_setImageWithURL:HJUserInfo.avatar.URL placeholderImage:[UIImage imageNamed:@"avatar"]];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.height.offset(80);
        make.top.offset(-30);
    }];
    
    UIImageView *QrCodeImageView = [UIImageView addToView:contentView];
    [QrCodeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.height.offset(190);
        make.top.offset(110);
    }];
    
    UIImageView *logoImageView = [UIImageView addToView:QrCodeImageView];
    logoImageView.image = [UIImage imageNamed:@"qrCode_logo_icon"];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    UILabel *nicknameLabel = [UILabel lableWithSuperView:contentView font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:HJUserInfo.nickname textAlignment:NSTextAlignmentLeft];
    [nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(avatarImageView.mas_bottom).offset(8);
        make.centerX.equalTo(avatarImageView).offset(0);
        make.width.mas_lessThanOrEqualTo(KScreenWidth - leftRightMargin * 4);
    }];
    
    UILabel *resetLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(12) color:UIColor.tj_868391Color title:@"Reset QR Code" textAlignment:NSTextAlignmentLeft];
    [resetLabel addTapGesturesWithTarget:self action:@selector(didClickResetButton)];
    [resetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(12);
        make.top.equalTo(QrCodeImageView.mas_bottom).offset(22);
    }];
    
    UIButton *resetButton = [UIButton addToView:contentView];
    [resetButton addTarget:self action:@selector(didClickResetButton) forControlEvents:UIControlEventTouchUpInside];
    [resetButton setImage:[UIImage imageNamed:@"qrCode_refresh"] forState:UIControlStateNormal];
    [resetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(resetLabel.mas_left).inset(5);
        make.centerY.equalTo(resetLabel);
        make.width.height.offset(16);
    }];
    
    UILabel *tipLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:@"Never miss out You deserve value from socializing" textAlignment:NSTextAlignmentLeft];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.inset(22);
        make.centerX.equalTo(avatarImageView).offset(0);
    }];
    
    UIImageView *bigLogoImageView = [UIImageView addToView:QrCodeImageView];
    bigLogoImageView.image = [UIImage imageNamed:@"qrCode_logo"];
    [bigLogoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(tipLabel.mas_top).inset(10);
        make.centerX.offset(0);
    }];
    
    HJButton *saveButton = [HJButton buttonWithSuperView:backgroundImageView font:UIFontMediumMake(12) color:UIColor.whiteColor title:@"Save"];
    [saveButton setImage:[UIImage imageNamed:@"qrCode_save_icon"] forState:UIControlStateNormal];
    saveButton.anyObject = @"save";
    saveButton.addCornerRadius(10);
    saveButton.backgroundColor = [UIColor.tj_512BEAColor colorWithAlphaComponent:0.44];
    saveButton.imagePosition = QMUIButtonImagePositionLeft;
    saveButton.spacingBetweenImageAndTitle = 5;
    [saveButton addTarget:self action:@selector(didClickSaveButton) forControlEvents:UIControlEventTouchUpInside];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.inset(16 + TabbarSafeBottomMargin);
        make.left.offset(leftRightMargin);
        make.right.equalTo(self.view.mas_centerX).inset(30);
        make.height.offset(buttonHeight);
    }];
    
    HJButton *shareButton = [HJButton buttonWithSuperView:backgroundImageView font:UIFontMediumMake(12) color:UIColor.tj_333333Color title:@"Share"];
    [shareButton setBackgroundImage:[UIImage imageWithContentsOfName:@"qrcodeShare_bg" type:@"png"] forState:UIControlStateNormal];
    [shareButton setImage:[UIImage imageNamed:@"qrCode_share_icon"] forState:UIControlStateNormal];
    shareButton.anyObject = @"share";
    shareButton.addCornerRadius(10);
    shareButton.backgroundColor = UIColor.whiteColor;
    shareButton.imagePosition = QMUIButtonImagePositionLeft;
    shareButton.spacingBetweenImageAndTitle = 5;
    [shareButton addTarget:self action:@selector(didClickShareButton) forControlEvents:UIControlEventTouchUpInside];
    [shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.height.equalTo(saveButton);
        make.right.inset(leftRightMargin);
        make.left.equalTo(saveButton.mas_right).inset(14);
    }];
    
    _QrCodeImageView = QrCodeImageView;
    
    [self addShareView];
    [self createQrCode];
//    dispatch_async_main_queue(^{
//    });
}

- (void)addShareView {
    
    UIImageView *contentView = [UIImageView addToView:self.view];
    contentView.image = [UIImage imageWithContentsOfName:@"qrcode_share_content_bg" type:@"png"];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(0);
        make.top.equalTo(self.view.mas_bottom);
        make.height.offset(530);
    }];
    
    UIImageView *avatarImageView = [UIImageView addToView:contentView];
    avatarImageView.addCornerRadius(24);
    [avatarImageView tj_setImageWithURL:HJUserInfo.avatar.URL placeholderImage:[UIImage imageNamed:@"avatar"]];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(48);
        make.left.inset(40);
        make.top.offset(78);
    }];
    
    UILabel *nicknameLabel = [UILabel lableWithSuperView:contentView font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:HJUserInfo.nickname textAlignment:NSTextAlignmentLeft];
    [nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(avatarImageView.mas_right).offset(12);
        make.centerY.equalTo(avatarImageView);
        make.right.mas_lessThanOrEqualTo(-leftRightMargin);
    }];
    
    UIImageView *QrCodeImageView = [UIImageView addToView:contentView];
    [QrCodeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.height.offset(196);
        make.top.offset(164);
    }];
    

    UILabel *operationTipLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(12) color:UIColor.tj_868391Color title:@"Open Kai > Scan to add friends" textAlignment:NSTextAlignmentLeft];
    [operationTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(QrCodeImageView.mas_bottom).offset(22);
    }];
    
 
    UILabel *tipLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:@"Take you into the era of decentralization" textAlignment:NSTextAlignmentLeft];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.inset(58);
        make.left.equalTo(avatarImageView);
    }];
    
    UIImageView *bigLogoImageView = [UIImageView addToView:QrCodeImageView];
    bigLogoImageView.image = [UIImage imageNamed:@"qrCode_logo"];
    [bigLogoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(tipLabel.mas_top).inset(8);
        make.left.equalTo(avatarImageView);
        make.width.offset(44);
        make.height.offset(21);
    }];
    
    _shareView = contentView;
    _shareQrCodeImageView = QrCodeImageView;
}

- (void)didClickResetButton {
    [HJAlertController alertInController:self title:@"Reset QR Code" message:@"Resett QR code will create a new one, the old code will be invalid." left:^(HJAlertAction * _Nonnull action) {
        action.title = @"Cancel";
        action.titleColor = UIColor.tj_868391Color;
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"OK";
        action.titleColor = UIColor.tj_mainColor;
        self -> _qrCodeDict = nil;
        [action setHandler:^{
             [self createQrCode];
        }];
    }];
}

- (void)createQrCode {
//    dispatch_async_queue(^{
        UIImage *image = [UIImage qrCodeImageWithContent:self.qrCodeDict.mj_JSONString withSize:196];
    self.QrCodeImageView.image = image;
    self.shareQrCodeImageView.image = image;
        dispatch_async_main_queue(^{
        });
//    });
}

- (void)didClickSaveButton {

    UIImage *shareImage = [HJTools convertViewToImage:self.shareView];
    UIImageWriteToSavedPhotosAlbum(shareImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error) {
        
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusNotDetermined) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"No access to Photos" message:@"We require access to your photos. Please select [Settings > Prvacy Photos] and enable access for \"Kai\" to all photos" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil]];
            [alert addAction:[UIAlertAction actionWithTitle:@"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *appSettings = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:appSettings]) {
                    [[UIApplication sharedApplication] openURL:appSettings options:@{} completionHandler:nil];
                }
            }]];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
        
        [HJHUD showErrorMessage:@"Save failed"];
    } else {
        [HJHUD showSucceedMessage:@"Saved successfully"];
    }
}

- (void)didClickShareButton {
    
    UIImage *shareImage = [HJTools convertViewToImage:self.shareView];
    NSString *localPath = @"qrCode.jpg".tj_documentsPath;
    [HJTools writeImageData:UIImageJPEGRepresentation(shareImage, 0.75) toLocalPath:localPath];
    NSURL *URL = [NSURL fileURLWithPath:localPath];
    
    HJShareController *shareController = [[HJShareController alloc] init];
    shareController.objects = @[URL];
    [HJTools.currentViewController presentViewController:shareController animated:YES completion:nil];
}

- (NSDictionary *)qrCodeDict {
    if (!_qrCodeDict) {
        _qrCodeDict = @{
            @"UID": HJUserInfo.no,
            @"date": @([NSDate.date timeIntervalSince1970])
        };
    }
    return _qrCodeDict;
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
 

@end
